package org.csu.new_jpetstore_backend.controller.front;

import com.alipay.api.AlipayApiException;
import org.csu.new_jpetstore_backend.common.CommonResponse;
import org.csu.new_jpetstore_backend.common.LoginResponse;
import org.csu.new_jpetstore_backend.entity.Account;
import org.csu.new_jpetstore_backend.entity.AliPayBean;
import org.csu.new_jpetstore_backend.entity.Log;
import org.csu.new_jpetstore_backend.service.LogService;
import org.csu.new_jpetstore_backend.service.PayService;
import org.csu.new_jpetstore_backend.service.impl.LogServiceImpl;
import org.csu.new_jpetstore_backend.service.impl.PayServiceImpl;
import org.csu.new_jpetstore_backend.util.JWTUtils;
import org.csu.new_jpetstore_backend.vo.CartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.csu.new_jpetstore_backend.service.impl.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.security.Security;
import java.util.*;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    AccountServiceImpl accountService;

    private PayService payService;
    @Autowired
    LogServiceImpl logService;
    /**日志对象*/
    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @GetMapping("/")
    public Account getCurrentAccount(HttpServletRequest req) {
        String username = (String) req.getAttribute("username");
        return accountService.selectAccountByUsername(username);
    }

    @PostMapping(value = "/login")
    public Object login(@RequestBody Account account){
        System.out.println(accountService);
        System.out.println(account.getUsername()+"     "+account.getPassword());
        Account account1 = accountService.selectAccountByUsername(account.getUsername());
        LoginResponse loginResponse = new LoginResponse();

        if(account1 == null){
            loginResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
            loginResponse.setMessage("Account is not exist!");
            return loginResponse;
        }else if(!account1.getPassword().equals(account.getPassword())){
            loginResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
            loginResponse.setMessage("Password is wrong!");
            return loginResponse;
        }else{
            loginResponse.setHttpStatus(HttpStatus.OK);
            loginResponse.setMessage("login success!");
            loginResponse.setAccount(account1);
            String token = JWTUtils.createToken(account1.getUsername(), account1.getEmail());
            loginResponse.setToken(token);
            return loginResponse;
        }
    }

    @PostMapping(value = "/register")
    public CommonResponse<Object> register(@RequestBody Account account){
        System.out.println(account.getUsername()+"------"+account.getPassword()+"------"+account.getEmail());
        CommonResponse<Object> response = accountService.register(account);
        return response;
    }

    @GetMapping(value = "/checkemail")
    public CommonResponse<Object> checkEmail(@RequestParam String email){
        System.out.println("markEmail!!!!"+email);
        CommonResponse<Object> response = accountService.checkEmail(email);
        return response;
    }

    @GetMapping(value = "/checkusername")
    public CommonResponse<Object> checkUsername(@RequestParam String username){
        System.out.println("markUsername!!!!"+username);
        CommonResponse<Object> response = accountService.checkUsername(username);
        return response;
    }

    @GetMapping(value = "/checkphone")
    public CommonResponse<Object> checkPhone(@RequestParam String phone){
        System.out.println("markPhone!!!!"+phone);
        CommonResponse<Object> response = accountService.checkPhone(phone);
        return response;
    }

    @PostMapping(value = "/modify")
    public CommonResponse<Object> modifyAccountInformation(@RequestBody Account account){
        System.out.println("mark!!!"+account);
        CommonResponse<Object> response = accountService.updateAccountInformation(account);
        return response;
    }

    @GetMapping("/cart")
    public CommonResponse<List<CartVO>> getCart(){
        return accountService.getCartByAccount("j2ee");
    }

    @ResponseBody
    @GetMapping("{id}/cart")
    public CommonResponse<List<CartVO>> getCartByAccount(@PathVariable("id") String username){
        return accountService.getCartByAccount(username);
    }

    @ResponseBody
    @PostMapping("{userid}/cart/{id}")
    public CommonResponse<List<CartVO>> updateCart(@PathVariable("userid") String username, @PathVariable("id") String itemId, @RequestParam String quantity){
        return accountService.updateCart(username, itemId, quantity);
    }

    @RequestMapping("/alipay")
    @ResponseBody
    public String aliPay(String outTradeNo, String subject, String totalAmount, String body)throws AlipayApiException {

        /*//logger.info("商户订单号为{},订单名称为{},付款金额为{},商品描述{}", orderId, subject, totalCost, body);
        logger.info("商户订单号为{},付款金额为{}", outTradeNo,  totalAmount);
        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        //alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
       // alipayBean.setBody(body);*/
        logger.info("商户订单号为{},订单名称为{},付款金额为{},商品描述{}", outTradeNo, subject, totalAmount, body);
        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);
        ///order/alipay(outTradeNo=${session.order.orderId},subject=${session.order.status},body=${session.order.orderDate} ,totalAmount=${session.order.totalPrice})}">支付<
        payService=new PayServiceImpl();
        return payService.aliPay(alipayBean);
    }
    @ResponseBody
    @PostMapping("/verification/{email}")
    public CommonResponse<String> verified(@PathVariable ("email") String email) throws MessagingException {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Properties props = new Properties();
//        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
//        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "587");
//        props.setProperty("mail.smtp.socketFactory.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
//        props.put("mail.smtp.port", "587");
        props.put("mail.user", "2801153431@qq.com");
        props.put("mail.password", "iinxteyzxgdmddia");
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userName = props.getProperty("mail.user");
                String password1 = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password1);
            }
        };
        Session mailSession = Session.getInstance(props, authenticator);
        MimeMessage message = new MimeMessage(mailSession);
        InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
        message.setFrom(form);
        InternetAddress to = new InternetAddress(email);
        message.setRecipient(Message.RecipientType.TO, to);
        message.setSubject("标题");
        String sendVerification = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            sendVerification += random.nextInt(10);
        }
        message.setContent(sendVerification, "text/html;charset=UTF-8");
        Transport.send(message);
        return CommonResponse.createForSuccess(sendVerification);
    }

    @GetMapping("/log")
    @ResponseBody
    public CommonResponse<List<Log>>getLog(HttpServletRequest req)
    {
        String username = (String) req.getAttribute("username");
        return logService.getTricks(username);
    }

    @ResponseBody
    @PostMapping("{userid}/addToCart/{id}")
    public CommonResponse<List<CartVO>> addToCart(@PathVariable("userid") String username, @PathVariable("id") String itemId,HttpServletRequest req){
        String usernameLog = (String) req.getAttribute("username");
        String logAction = "add to cart" + itemId;
        System.out.println(usernameLog);
        System.out.println(logAction);
        logService.addLog(usernameLog, logAction);
        return accountService.addToCart(username, itemId);
    }


}
